package controllers

import (
	"atcle/models"
	beego "github.com/beego/beego/v2/server/web"
)

type AtcleController struct {
	beego.Controller
}

func (c *AtcleController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	read, _ := c.GetInt("read")
	like, _ := c.GetInt("like")
	comment, _ := c.GetInt("comment")
	atcle := models.Atcle{
		Title:         c.GetString("title"),
		Image:         models.Getimage(c.GetFile("image")),
		Classify:      c.GetString("classify"),
		Abstract:      c.GetString("abstract"),
		Data:          c.GetString("data"),
		User:          c.GetString("name"),
		From:          c.GetString("form"),
		ReadCount:     read,
		LikeCount:     like,
		CommentCount:  comment,
		Issus:         c.GetString("issus"),
		Top:           c.GetString("top"),
		CommentSwitch: c.GetString("comments"),
		Excellent:     c.GetString("excellent"),
	}
	err := models.DB.Create(&atcle).Error
	if err != nil {
		c.Data["jaon"] = models.Msg{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["jaon"] = models.Msg{
		Code: 200,
		Msg:  "上传成功",
		Data: nil,
	}
	c.ServeJSON()
}
func (c *AtcleController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	const limit = 5
	page, _ := c.GetInt("page", 1)
	var atcles []models.Atcle
	name := c.GetString("name")
	err := models.DB.Limit(limit).Offset((page-1)*limit).Where("title like ?", "%"+name+"%").Order("id,desc").Find(&atcles).Error
	if err != nil {
		c.Data["jaon"] = models.Msg{
			Code: 0,
			Msg:  "获取失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["jaon"] = models.Msg{
		Code: 200,
		Msg:  "获取成功",
		Data: atcles,
	}
	c.ServeJSON()
}
